<?php

    class Application_Plugin_SocialPlugin extends Zend_Controller_Plugin_Abstract
    {

        public function preDispatch(Zend_Controller_Request_Abstract $request)
        {
            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (empty($y))
            {
                $this->facebookLogin();
                $this->twitterLogin();
                $this->linkedinLogin();
            }
        }

        public function facebookLogin()
        {
            require_once APPLICATION_PATH . '/../assets/social/facebook/facebook.php';
            $facebook_auth_array = array();

// Create our Application instance (replace this with your appId and secret).
            $facebook = new Facebook(array(
                'appId' => FACEBOOK_APP_ID,
                'secret' => FACEBOOK_SECRET_ID,
            ));

// Get User ID
            $user = $facebook->getUser();

// Login or logout url will be needed depending on current user state.
            if ($user)
            {
                $logoutUrl = $facebook->getLogoutUrl();
            }
            else
            {
                $loginUrl = $facebook->getLoginUrl(array(
                    "redirect_uri" => FACEBOOK_CALLBACK_URL,
                    "scope" => "email"
                ));
            }

            $facebook_auth_array = array(
                "login_url" => $facebook->getLoginUrl(array(
                    "redirect_uri" => FACEBOOK_CALLBACK_URL,
                    "scope" => "email"
                )),
                "logout_url" => $facebook->getLogoutUrl()
            );

            Zend_Registry::set("FACEBOOK_AUTH", $facebook_auth_array);
        }

        public function twitterLogin()
        {
            require_once APPLICATION_PATH . '/../assets/social/twitter/twitteroauth/twitteroauth.php';

            if (!isset($_REQUEST["oauth_verifier"]))
            {
                $connection = new TwitterOAuth(TWITTER_APP_ID, TWITTER_SECRET_ID);
                $temporary_credentials = $connection->getRequestToken(TWITTER_CALLBACK_URL);
                /* Save temporary credentials to session. */
                $_SESSION['oauth_token'] = $token = $temporary_credentials['oauth_token'];
                $_SESSION['oauth_token_secret'] = $temporary_credentials['oauth_token_secret'];
                
//                prd($temporary_credentials);

                $redirect_url = $connection->getAuthorizeURL($token);
                Zend_Registry::set("TWITTER_AUTH", array("login_url" => $redirect_url));
                Zend_Registry::set("TEST", $_SESSION);
            }
        }

        public function linkedinLogin()
        {

            // Change these
            define('API_KEY', LINKEDIN_APP_ID);
            define('API_SECRET', LINKEDIN_APP_SECRET);
            define('REDIRECT_URI', LINKEDIN_CALLBACK_URL);
            define('SCOPE', 'r_fullprofile r_emailaddress rw_nus');

            function getAuthorizationCode()
            {
                $params = array('response_type' => 'code',
                    'client_id' => API_KEY,
                    'scope' => SCOPE,
                    'state' => uniqid('', true), // unique long string
                    'redirect_uri' => REDIRECT_URI,
                );

                // Authentication request
                $url = 'https://www.linkedin.com/uas/oauth2/authorization?' . http_build_query($params);

                // Needed to identify request when it returns to us
                $_SESSION['state'] = $params['state'];

                // Redirect user to authenticate
//                header("Location: $url");
                Zend_Registry::set("LINKEDIN_AUTH", array("login_url" => $url));
//                exit;
            }

            getAuthorizationCode();

            function getAccessToken()
            {
                $params = array('grant_type' => 'authorization_code',
                    'client_id' => API_KEY,
                    'client_secret' => API_SECRET,
                    'code' => $_GET['code'],
                    'redirect_uri' => REDIRECT_URI,
                );

                // Access Token request
                $url = 'https://www.linkedin.com/uas/oauth2/accessToken?' . http_build_query($params);

                // Tell streams to make a POST request
                $context = stream_context_create(
                        array('http' =>
                            array('method' => 'POST',
                            )
                        )
                );

                // Retrieve access token information
                $response = file_get_contents($url, false, $context);

                // Native PHP object, please
                $token = json_decode($response);

                // Store access token and expiration time
                $_SESSION['access_token'] = $token->access_token; // guard this!
                $_SESSION['expires_in'] = $token->expires_in; // relative time (in seconds)
                $_SESSION['expires_at'] = time() + $_SESSION['expires_in']; // absolute time

                return true;
            }

        }

    }

?>